package com.codejiwei.flink.practice;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author jiwei
 * @description 滑动时间窗口
 * @date 2023/5/23 10:50
 */
public class Flink_Windows_Sliding {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(10);

        env.socketTextStream("localhost", 8889)
                .flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                        Arrays.stream(s.split("\\W+")).forEach(word -> collector.collect(Tuple2.of(word, 1L)));
                    }
                })
                .keyBy(t -> t.f0)
                //TODO 注意
                // 滑动窗口 < 滑动步长 可能丢数据
                // 滑动窗口 > 滑动步长 可能重复数据
                // 滑动窗口 = 滑动步长 等同于滚动窗口
                .window(SlidingProcessingTimeWindows.of(Time.seconds(5), Time.seconds(5)))
//                .countWindow(10)
                .sum(1)
                .print();

        env.execute();
    }
}
